﻿using BMCShowView.Portal.Models;
using BMCShowView.Portal.ViewModels;
using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Mvc;

namespace BMCShowView.Portal.Controllers
{
    public class BackendController : Controller
    {
        // GET: Backend
        public ActionResult Index()
        {
            using (var context = new BmcContext())
            {
                return View(new BackendViewModel
                {
                    Announcement = context.Announcements.OrderByDescending(x => x.CreateTime).FirstOrDefault() ?? new Announcement(),
                    Remark = context.Remarks.OrderByDescending(x => x.CreateTime).FirstOrDefault() ?? new Remark()
                });
            }
        }

        [HttpPost]
        public ActionResult Index(
            [Form] string announcement,
            [Form] string remark)
        {
            if (announcement == null && remark == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            object model;
            using (var context = new BmcContext())
            {
                if (announcement != null)
                {
                    context.Announcements.Add((Announcement)(model = new Announcement
                    {
                        Content = announcement,
                        CreateTime = DateTime.Now
                    }));
                }
                else
                {
                    context.Remarks.Add((Remark)(model = new Remark
                    {
                        Content = remark,
                        CreateTime = DateTime.Now
                    }));
                }
                context.SaveChanges();
            }

            lock (HomeController.HomeLock)
            {
                Monitor.PulseAll(HomeController.HomeLock);
            }

            return Json(model);
        }
    }
}